#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
创建默认用户脚本
直接创建数据库表和默认用户账号
"""

import os
import sys
import uuid
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash

# 确保instance目录存在
instance_dir = 'instance'
if not os.path.exists(instance_dir):
    print(f"创建instance目录: {instance_dir}")
    os.makedirs(instance_dir)

# 创建简单的Flask应用
app = Flask(__name__)
# 使用绝对路径
basedir = os.path.abspath(os.path.dirname(__file__))
db_path = os.path.join(basedir, 'instance', 'vulnerability.db')
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
print(f"数据库路径: {app.config['SQLALCHEMY_DATABASE_URI']}")

# 初始化数据库
db = SQLAlchemy(app)

# 直接定义User模型类
class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.String(50), primary_key=True, default=lambda: str(uuid.uuid4()))
    username = db.Column(db.String(80), unique=True, nullable=False, index=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(200), nullable=False)
    role = db.Column(db.String(20), nullable=False, default='user')
    organization = db.Column(db.String(100))
    department = db.Column(db.String(100))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    last_login_at = db.Column(db.DateTime)
    is_active = db.Column(db.Boolean, default=True)
    
    def set_password(self, password):
        # 使用werkzeug的安全哈希函数
        self.password_hash = generate_password_hash(password)
    
    def __repr__(self):
        return f'<User {self.username}>'

# 直接定义UserPreference模型类
class UserPreference(db.Model):
    __tablename__ = 'user_preferences'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.String(50), db.ForeignKey('users.id'), unique=True)
    theme = db.Column(db.String(20), default='light')
    language = db.Column(db.String(10), default='zh-CN')
    notifications_enabled = db.Column(db.Boolean, default=True)

# 确保在应用上下文中运行
with app.app_context():
    # 删除旧的数据库文件
    if os.path.exists(db_path):
        print(f"删除旧数据库文件: {db_path}")
        os.remove(db_path)
    
    # 创建所有表
    print("创建数据库表...")
    db.create_all()
    print("✓ 数据库表创建成功！")
    
    # 确认表是否已创建
    from sqlalchemy import inspect
    inspector = inspect(db.engine)
    existing_tables = inspector.get_table_names()
    print(f"数据库中的表: {existing_tables}")
    
    # 创建默认用户
    print("\n创建默认用户账号...")
    
    # 创建管理员用户
    admin_user = User(
        id='1',
        username='admin',
        email='admin@example.com',
        role='admin',
        organization='系统管理',
        department='安全运维'
    )
    admin_user.set_password('admin123')
    db.session.add(admin_user)
    
    # 创建普通用户
    regular_user = User(
        id='2',
        username='user1',
        email='user1@example.com',
        role='user',
        organization='测试部门',
        department='开发组'
    )
    regular_user.set_password('user123')
    db.session.add(regular_user)
    
    try:
        db.session.commit()
        print("✓ 默认用户创建成功！")
        print("\n默认账号信息：")
        print("  管理员: username=admin, password=admin123")
        print("  普通用户: username=user1, password=user123")
        
        # 验证用户是否创建成功
        users = User.query.all()
        print(f"\n数据库中现有用户数: {len(users)}")
        for user in users:
            print(f"  - {user.username} (角色: {user.role})")
            
    except Exception as e:
        db.session.rollback()
        print(f"✗ 创建默认用户失败: {str(e)}")
    
    print("\n用户创建脚本执行完成。")